package me.zhujin.java.learnjava.myserver;

import me.zhujin.java.learnjava.myserver.threadpool.CountableThreadPool;
import me.zhujin.java.learnjava.myserver.util.CloseUtil;

import java.io.IOException;
import java.net.ServerSocket;
import java.nio.charset.Charset;

/**
 * server
 * Created by zhujin on 10/20/16.
 * blog:www.zhujin.me
 * email: zhujin.nova@gmail.com
 */
public class MyServer {

    private static int PORT = 8080;
    private static int threadCount = 8;
    private static String BLOCK = " ";
    //carriage return linefeed
    private static String CRLR = "\r\n";

    private ServerSocket serverSocket;
    private volatile boolean shutDown = false;

    static  CountableThreadPool  threadPool = new CountableThreadPool(threadCount);

    public void start() {
        try {
            start(PORT);
        } catch (IOException e) {
            e.printStackTrace();
            shutdown();
        }
    }

    public void start(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        receive();
    }


    public void shutdown() {
        shutDown = true;
        threadPool.shutdown();
        CloseUtil.closeSocket(serverSocket);

    }


    public void receive() throws IOException {
//        while (!shutDown) {
//            new Thread(new MyDispatcher(serverSocket.accept())).start();
//        }

        // edit threadPool
        while (!shutDown) {
            threadPool.execute(new MyDispatcher(serverSocket.accept()));
        }

    }

    public static void main(String[] args) {
        MyServer server = new MyServer();
        server.start();
//        String  orign = "test";
//        byte[] data = orign.getBytes();
//        String requestInfo = new String(data, 0, data.length, Charset.defaultCharset());
//        System.out.println(requestInfo);
    }

}
